package com.mybatis.basic.fileupload;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;

/**************************************
 * 
 * 上传文件至阿里云OSS文件服务器
 * @author Administrator
 *
 **************************************
 */
public class FileUploadByAliOSS extends FileUploadBase{

	private static final Logger log = Logger.getLogger(FileUploadByAliOSS.class);

	private static Properties oss;

	static {
		try {
			InputStream in = Thread.currentThread()
					.getContextClassLoader()
					.getResourceAsStream("aliyun-oss.properties");
			oss = new Properties();
			oss.load(in);
			log.info("加载OSS配置信息完成------------"+oss);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//阿里云对象存储OSS地址
	private final String endpoint = oss.getProperty("endpoint");
	/**
	 *  云账号AccessKey有所有API访问权限，
	 *  建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，
	 *  请登录 https://ram.console.aliyun.com 创建
	 */
	private final String accessKeyId = oss.getProperty("accessKeyId");
	private final String accessKeySecret = oss.getProperty("accessKeySecret");
	private final String imagePrefix = oss.getProperty("imagePrefix");
	private final String videoPrefix = oss.getProperty("videoPrefix");
	private final String BucketName_images = oss.getProperty("bucketNameImages");
	private final String BucketName_videos = oss.getProperty("bucketNameVideos");
	private final String dirName = oss.getProperty("dirName");

	/**
	 * 文件上传到阿里云对象存储OSS服务器
	 * @param inputStream 网络流
	 * @param fileName 文件名
	 * @param type 1：图片上传 2：视频上传
	 * @return
	 */
	public String mediaToAliOSS(MultipartFile file,int type){
		OSSClient ossClient = null;
		String filePath = "";
		try {
			//上传的文件名
			String fileName_ = file.getOriginalFilename();
			//文件后缀，不包含 . 
			String suffix_ = fileName_.substring(fileName_.lastIndexOf(".")+1);
			//判断是否上传的不允许上传的文件类型
			if(Arrays.asList(getAllowFileType()).contains(suffix_)){
				return "不允许上传该文件类型";
			}
			long fileSize_ = file.getSize();
			if(fileSize_>getAllowSize()){
				return "上传的文件超出允许的最大值";
			}
			// 文件名
			String newFileName = createFileName()+"."+suffix_;
			// 创建OSSClient实例
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			// 上传
			ossClient.putObject(type==1?BucketName_images:BucketName_videos, dirName+"/"+newFileName, file.getInputStream());
			// 文件名称
			setFileName(newFileName);//  fileName = newFileName;
			// 文件路径
			String prefix = type==1?imagePrefix:videoPrefix;
			filePath = prefix+"/"+dirName+"/"+newFileName;
			setFilePath(filePath);
		} catch (Exception e) {
			log.error("上传文件到OSS失败");
			e.printStackTrace();
			filePath = "";
		} finally {
			if(null!=ossClient){
				// 关闭client
				ossClient.shutdown();
			}
		}
		return filePath;
	}

	/**
	 * 删除AliOSS单个文件
	 * @param fileName 文件名
	 * @param type 图片还是视频 1图片 2视频
	 * @return
	 */
	public boolean delFileByAliOSS(String fileName,int type){
		OSSClient ossClient = null;
		boolean result = false;
		try {
			ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
			//删除文件
			ossClient.deleteObject(type==1?BucketName_images:BucketName_videos, dirName+"/"+fileName);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("程序错误，图片删除失败");
		} finally {
			if (null != ossClient) {
				ossClient.shutdown();
			}
		}
		return result;
	}

	/**
	 * 删除AliOSS多个文件
	 * @param fileNames 多个文件名
	 * @param type 图片还是视频 1图片 2视频
	 * @return
	 */
	public List<String> delFilesByAliOSS(List<String> fileNames,int type){
		OSSClient ossClient = null;
		List<String> result = null;
		try {
			//遍历文件名集合，增加前缀目录为指定目录，并生成新的文件名集合
			List<String> newFileNames = new ArrayList<String>(0);
			for (String string : fileNames) {
				string = dirName+"/"+string;
				newFileNames.add(string);
			}
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(type==1?BucketName_images:BucketName_videos);
			/* 
			 *  设置删除信息返回模式
    		 *	详细模式：返回的成功删除Object的结果，即DeleteObjectsResult.getDeletedObjects，默认模式；
    		 *	简单模式：返回的删除过程中出错的Object结果，即DeleteObjectsResult.getDeletedObjects。
    		 *	true简单模式，false详细模式
			 */
			deleteObjectsRequest.setQuiet(true);
			// 设置需要删除的文件名，List<String> 。
			deleteObjectsRequest.setKeys(newFileNames);
			// 删除文件
			DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
			// 删除结果
			result = deleteObjectsResult.getDeletedObjects();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(null != ossClient){
				ossClient.shutdown();
			}
		}
		return result;
	}
}
